package cn.chart.shiro.realm;

import cn.chart.dao.UsersMapper;
import cn.chart.domain.Users;
import cn.chart.domain.UsersExample;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.List;

public class CustomRealm extends AuthorizingRealm{ //授权realm

    @Resource
    private UsersMapper usersMapper;

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = getPasswordByUsername(username);
        if(password==null)
            return null;
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,"customRealm");
        return authenticationInfo;
    }

    private String getPasswordByUsername(String username) {
        UsersExample usersExample = new UsersExample();
        UsersExample.Criteria criteria= usersExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<Users> usersList =  usersMapper.selectByExample(usersExample);
        if(usersList==null||usersList.size()==0)
            return null;
        System.out.println(usersList.get(0).getUsername()+","+usersList.get(0).getPassword());
        return usersList.get(0).getPassword();
    }
}
